// 使用 require 动态导入 rollup-plugin-terser，绕过 TypeScript 类型检查
import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv, splitVendorChunkPlugin } from 'vite'
import vue from '@vitejs/plugin-vue'
// @ts-ignore - 忽略类型错误，rollup-plugin-terser包有类型声明文件但导出不兼容
import { terser } from 'rollup-plugin-terser'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver, ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import svgLoader from 'vite-svg-loader'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const isProduction = mode === 'production';
  return {
    // base: isProduction ? '/production/' : '/',
    base: '/',
    plugins: [
      vue(),
      // 自动按需引入 Ant Design Vue 组件
      Components({
        resolvers: [
          AntDesignVueResolver({
            importStyle: false, // css in js
            resolveIcons: true,
          }),
          ElementPlusResolver(),
        ],
        dts: true,
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      // 允许将SVG作为Vue组件导入
      svgLoader()
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    server: {
      port: 3000,
      open: true,
      proxy: {
        '/worker': {
          // target: 'http://192.168.1.10/console/api',
          target: 'https://kefu.hlsclothing.net',
          changeOrigin: true,
          // rewrite: path => path.replace(/^\/api\/goview\/aiapi/, '')
        },
        '/api': {
          target: 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    build: {
      // 减少内存消耗，提高构建效率
      emptyOutDir: true,
      // 启用CSS代码分割
      cssCodeSplit: true,
      // 减小CSS体积
      cssMinify: true,
      // 禁用源码映射
      sourcemap: false,
      // 使用terser进行代码压缩
      minify: 'terser',
      // 提高构建性能，减少内存消耗
      minifyInternalExports: true,
      // 启用gzip压缩
      reportCompressedSize: true,
      // 打包时清除console和debugger
      terserOptions: {
        compress: {
          // drop_console: isProduction,
          // drop_debugger: true,
          // pure_funcs: isProduction ? ['console.log', 'console.info', 'console.debug'] : [],
        },
        format: {
          comments: false, // 移除所有注释
        },
        mangle: true, // 混淆变量名
      },
      // 分块大小警告限制 - 提高警告阈值以接受较大包
      // 注：如果继续拆分，会导致组件间引用顺序问题
      chunkSizeWarningLimit: 1000,
      // 启用渐进式Web应用配置
      assetsInlineLimit: 4096, // 4kb以下的资源内联为base64
      rollupOptions: {
        input: {
          main: path.resolve(__dirname, 'index.html'),
        },
        output: {
          // 使用函数方式实现代码分割，以解决类型兼容性问题
          manualChunks: (id) => {
            // 基础框架运行时
            if (id.includes('node_modules/vue') ||
                id.includes('node_modules/vue-router') ||
                id.includes('node_modules/pinia')) {
              return 'runtime';
            }

            // 工具库
            if (id.includes('node_modules/dayjs') ||
                id.includes('node_modules/mitt') ||
                id.includes('node_modules/lodash') ||
                id.includes('node_modules/vue-i18n') ||
                id.includes('node_modules/pinia-plugin-persistedstate')) {
              return 'vendor-utils';
            }

            // 图标库
            if (id.includes('@ant-design/icons-vue')) {
              return 'vendor-icons';
            }

            // ant-design-vue 组件库，采用整体打包策略
            // 将所有组件合并到一个包中，彻底解决初始化顺序问题
            if (id.includes('node_modules/ant-design-vue')) {
              // 所有Ant Design Vue组件都放入同一个包中
              return 'antd';
            }

            // 其他第三方库
            if (id.includes('node_modules/')) {
              return 'vendors';
            }

            // 用户页面拆分
            if (id.includes('/src/views/user/') || id.includes('/src/pages/user/')) {
              // 订单相关页面
              if (id.includes('OrdersView') ||
                  id.includes('CheckoutView') ||
                  id.includes('CheckoutStep')) {
                return 'user-orders';
              }

              // 用户资料和设置相关页面
              if (id.includes('ProfileView') ||
                  id.includes('SettingsView') ||
                  id.includes('AddressesView')) {
                return 'user-profile';
              }

              // 购物车相关页面
              if (id.includes('CartView') ||
                  id.includes('FavoritesView')) {
                return 'user-cart';
              }

              // 积分和优惠券相关页面
              if (id.includes('PointsView') ||
                  id.includes('CouponsView')) {
                return 'user-rewards';
              }

              // 其他用户页面
              return 'user-other';
            }

            return undefined;
          },
          // 用于从入口点创建的块的打包输出格式
          // 将使用原始文件名作为参考，并添加内容哈希
          entryFileNames: 'assets/[name]-[hash].js',
          chunkFileNames: (chunkInfo) => {
            const { name } = chunkInfo;

            // 处理从node_modules导入的依赖库
            if (name && name.includes('node_modules')) {
              // ant-design-vue相关文件
              if (name.includes('ant-design-vue')) {
                return 'assets/vendor/antd/[name]-[hash].js';
              }
              return 'assets/vendor/deps/[name]-[hash].js';
            }

            // 处理src下的视图
            if (name && (name.includes('views') || name.includes('pages'))) {
              // 用户相关视图
              if (name.includes('user')) {
                return 'assets/pages/user/[name]-[hash].js';
              }
              return 'assets/pages/[name]-[hash].js';
            }

            // 处理组件
            if (name && name.includes('components')) {
              return 'assets/components/[name]-[hash].js';
            }

            // 处理ant-design预定义包
            if (name === 'antd') {
              return 'assets/vendor/antd/[name]-[hash].js';
            }

            // 处理预定义的chunks
            if (name === 'runtime' ||
                name === 'vendor-utils' ||
                name === 'vendor-icons' ||
                name === 'vendors' ||
                name && name.startsWith('user-')) {
              return 'assets/vendor/[name]-[hash].js';
            }

            return 'assets/[name]-[hash].js';
          },
          assetFileNames: (assetInfo) => {
            if (!assetInfo.name) return 'assets/[name]-[hash][extname]';

            // 图片资源
            if (/\.(png|jpe?g|gif|svg|webp|ico)(\?.*)?$/.test(assetInfo.name)) {
              return `assets/img/[name]-[hash][extname]`;
            }

            // 字体资源
            if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
              return `assets/fonts/[name]-[hash][extname]`;
            }

            // 媒体资源
            if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)) {
              return `assets/media/[name]-[hash][extname]`;
            }

            // 样式表
            if (/\.(css)$/i.test(assetInfo.name)) {
              return `assets/css/[name]-[hash][extname]`;
            }

            // 其他资源
            return `assets/[name]-[hash][extname]`;
          }
        },
        // 忽略打包后警告
        onwarn(warning, warn) {
          // 忽略循环依赖警告
          if (warning.code === 'CIRCULAR_DEPENDENCY') return;
          warn(warning);
        }
      }
    },
    optimizeDeps: {
      // 预构建分析包含的依赖
      include: [
        'vue',
        'vue-router',
        'pinia',
        'vue-i18n',
        'dayjs',
        'mitt',
        'swiper',
        'swiper/vue'
      ],
      // 强制排除不需要预构建的依赖
      exclude: []
    },
    // 添加Vite预构建缓存
    cacheDir: '.vite_cache'
  };
});

